package study.springcloud.discovery.consul.support.consul;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.NewService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.HeartbeatProperties;
import org.springframework.cloud.consul.discovery.TtlScheduler;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistration;
import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 *
 */
@Slf4j
public class MyConsulServiceRegistry extends ConsulServiceRegistry {

    private ConfigurableEnvironment environment;

    public MyConsulServiceRegistry(ConfigurableEnvironment environment,
                                   ConsulClient client,
                                   ConsulDiscoveryProperties properties,
                                   TtlScheduler ttlScheduler,
                                   HeartbeatProperties heartbeatProperties) {
        super(client, properties, ttlScheduler, heartbeatProperties);
        this.environment = environment;
    }

    @Override
    public void register(ConsulRegistration registration) {
        setService(registration);
        log.info(">>>>>> Register service with consul:{}", registration.getService().getId());
        super.register(registration);
    }

    @Override
    public void deregister(ConsulRegistration registration) {
        setService(registration);
        log.info(">>>>>> Deregister service with consul:{}", registration.getService().getId());
        super.deregister(registration);
    }

    private void setService(ConsulRegistration registration) {
        //
        String cluster = environment.getProperty("spring.application.cluster");
        //服务信息
        NewService service = registration.getService();
        String serviceName = service.getName();
        if (StringUtils.isNotBlank(serviceName) &&
                StringUtils.isNotBlank(cluster) &&
                !serviceName.contains(cluster)) {
            serviceName = String.join("-", serviceName, cluster);
        }
        //生成新 id
        String newId = String.join("-", serviceName,
                service.getAddress(),
                String.valueOf(service.getPort()));
        service.setId(newId);
    }
}
